package com.wetao.module_pen.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitPenDataReq;
import com.wetao.lib_common.bean.request.CommitPenDataReq_page;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExam;
import com.wetao.lib_common.greendao.model.ExamListen;
import com.wetao.lib_common.greendao.model.PagePicture;
import com.wetao.lib_common.greendao.model.PagePictureGrid;
import com.wetao.lib_common.greendao.model.PenOffLineGridInfo;
import com.wetao.lib_common.net.RetryWithDelay;
import com.wetao.lib_common.net.RxUtils;
import com.wetao.lib_common.net.ServerUtils;
import com.wetao.lib_common.net.callback.RequestCallback;
import com.wetao.lib_common.net.callback.RxErrorHandler;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.module_pen.R;
import com.wetao.module_pen.R2;


import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

public class PenSubmitFragmentAdapter extends RecyclerView.Adapter{
    private List<PenOffLineGridInfo> mData;
    private int mCount;
    private int mCurSelect;
    private Context mContext;
    private int mOssCount = 0;
    private List<OssParams> mOssParamsList = new ArrayList<>();
    private boolean mIsSubmitSuccess = true;

    public PenSubmitFragmentAdapter(Context context) {
        this.mContext = context;
    }

    public void updateData(List<PenOffLineGridInfo> data) {
        mData = data;
        notifyDataSetChanged();
    }

    public void setmCount(int count) {
        mCount = count;
    }

    public void setmCurSelect(int curSelect) {
        mCurSelect = curSelect;
    }

    public int getmCurSelect() {
        return mCurSelect;
    }

    public int getmCount() {
        return mCount;
    }

    public void setAllSelect(boolean isSelect) {
        if(isSelect) {
            mCurSelect = mCount;
        } else {
            mCurSelect = 0;
        }

        if(mData != null) {
            for (PenOffLineGridInfo item : mData) {
                item.isSelect = isSelect;
            }
            notifyDataSetChanged();
        }
    }
    public boolean isAllSelect() {
        if(mCurSelect == 0) {
            return  false;
        }
        return mCurSelect == mCount;
    }

    public PenOffLineGridInfo getPositionData(int position) {
        if(mData != null && position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    public void setSubmit() {
        DialogXUtil.waitDialogShow("提交作答数据中...");
        boolean temp_select = false;
        mOssCount = 0;
        mOssParamsList.clear();
        mIsSubmitSuccess = true;
        for(PenOffLineGridInfo item : mData) {
            if(item.showType.intValue() == 1) {
                if(item.isSelect) {
                    temp_select = true;
                } else {
                    temp_select = false;
                }
            } else if(item.showType.intValue() == 2 && temp_select) {
                String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
                final String uploadFileName = studentId + "_" + item.getExamId() + "_" + item.getPicId() + "_"  + System.currentTimeMillis() + ".png";
                String picFilePath_c = null;

                picFilePath_c = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "f", "" + item.getPicId(), "");


                File file_c = new File(picFilePath_c);
                if(file_c.exists()) {
                    mOssCount++;
                    OssParams ossParams = new OssParams(item.getPicId(), null, uploadFileName, picFilePath_c);
                    mOssParamsList.add(ossParams);
                    //UploadOss.getInstance().upload2OSS(uploadFileName, picFilePath_c, ossUploadListener, ossParams);
                }
            }
        }
        osssUploadByOssCount();
        isOssSuccess();
    }

    private void osssUploadByOssCount() {
        if(mOssCount > 0) {
            OssParams params = mOssParamsList.get(mOssParamsList.size() - mOssCount);
            UploadOss.getInstance().upload2OSS(params.getUploadFileName(), params.getFilePath(), ossUploadListener, params);
        }
    }

    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            saveOssPathToDb(ossParams, uploadFile);
            mOssCount--;
            isOssSuccess();
            osssUploadByOssCount();
            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            mOssCount--;
            mIsSubmitSuccess = false;
            isOssSuccess();
            return null;
        }
    };

    private void saveOssPathToDb(OssParams ossParams, String uploadFile) {
        PenOffLineGridInfo penOffLineGridInfo = DBUtils.getInstance(mContext).getPenOffLineGridInfoByPicId((int)ossParams.getId());
        if(penOffLineGridInfo != null) {
            penOffLineGridInfo.setOssPath(uploadFile);
            DBUtils.getInstance(mContext).updatePenOffLineGridInfo(penOffLineGridInfo);
        }
        for(PenOffLineGridInfo item : mData) {
            if(item.getPicId().intValue() == ossParams.getId()) {
                item.setOssPath(uploadFile);
            }
        }
    }

    private void isOssSuccess() {
        LogUtils.i("m1: isOssSuccess: mOssCount=" + mOssCount + ", mIssubmitSuccess=" + mIsSubmitSuccess);
        if(mOssCount == 0 && mIsSubmitSuccess) {
            submitData_pre();
        } else {
            isSubmitSuccess();
        }
    }

    private void submitData_pre() {
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        String penMac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
        CommitPenDataReq req = new CommitPenDataReq(studentId, penMac, 2, ComUtil.getStringDate(), ComUtil.getStringDate(), null, null);
        List<CommitPenDataReq_page> pageVos = new ArrayList<>();
        boolean temp_select = false;
        long begin_time = 0;
        for(PenOffLineGridInfo item : mData) {
            long begin_time_temp = 0;
            try {
                begin_time_temp =  Long.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(item.getBeginTime()).getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if( begin_time == 0) {
                begin_time = begin_time_temp;
            } else {
                if(begin_time_temp < begin_time) {
                    begin_time = begin_time_temp;
                }
            }

            if(item.showType.intValue() == 1) {
                if(item.isSelect) {
                    temp_select = true;
                } else {
                    temp_select = false;
                }
            } else if(item.showType.intValue() == 2 && temp_select && !StringUtil.isEmpty(item.getOssPath())) {
                CommitPenDataReq_page page = new CommitPenDataReq_page(item.getPicId(), item.getOssPath(), null, item.getScale());
                pageVos.add(page);
            }
        }
        if(begin_time > System.currentTimeMillis()) {
            begin_time = System.currentTimeMillis();
        }
        String begin_time_str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(begin_time));
        req.setBeginTime(begin_time_str);

        req.setPageVos(pageVos);
        if(pageVos.size() == 0) {
            DialogXUtil.waitDialogDismiss();
            ToastUtil.initToast("提交失败，没有找到要提交的图片");
            return;
        }

        String json = JsonUtils.toJson(req);
        LogUtils.i("m1: 提交作答的json:" +json);

        RequestBody requestBody =  RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json);
        ServerUtils.getCommonApi().studentExamCommitPenData(requestBody)
                .retryWhen(new RetryWithDelay(3,2))
                .compose(RxUtils.<BaseResponse>getSchedulerTransformer())
                .subscribe(new RequestCallback<BaseResponse>(mContext, RxErrorHandler.getInstance(),false,false) {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        super.onNext(baseResponse);
                        if(baseResponse.getCode() == 0){

                            int examId = -1;
                            Iterator<PenOffLineGridInfo> it = mData.iterator();
                            while (it.hasNext()) {
                                PenOffLineGridInfo item = it.next();
                                 if(item.showType.intValue() == 1 && item.isSelect) {
                                     examId = item.getExamId();
                                     List<PenOffLineGridInfo> info_temp = DBUtils.getInstance(mContext).getPenOffLineGridInfoByExamId(examId);
                                     if(info_temp != null && info_temp.size() > 0) {
                                         for(PenOffLineGridInfo info_temp_item : info_temp) {
                                             info_temp_item.setBeginTime(null);
                                             info_temp_item.setFinishTime(null);
                                             info_temp_item.setOssPath(null);
                                             info_temp_item.setIsWrite(false);
                                             DBUtils.getInstance(mContext).updatePenOffLineGridInfo(info_temp_item);
                                         }
                                     }
                                     //DBUtils.getInstance(mContext).deletePenOffLineGridInfoByExamid(examId);
                                     deleteDataToDb(examId);
                                     mCount--;
                                     mCurSelect--;
                                }

                                if(item.getExamId() != null && item.getExamId().intValue() == examId) {
                                    deleteDataAndFile(item, it);
                                }
                            }

                            if(listener != null) {
                                listener.onRefrshSelect();
                            }
                            notifyDataSetChanged();

                            isSubmitSuccess();

                        }else{
                            ToastUtil.initToast("出错了：" + baseResponse.getMsg());
                            mIsSubmitSuccess = false;
                            isSubmitSuccess();
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtil.initToast("出错了：" + e.getMessage());
                        mIsSubmitSuccess = false;
                        isSubmitSuccess();
                    }
                });
    }

    private void deleteDataAndFile(PenOffLineGridInfo item, Iterator<PenOffLineGridInfo> it) {
        if(item.showType.intValue() == 2) {
            String picFilePath_b = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "b", "" + item.getPicId(), "");
            String picFilePath_f = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "f", "" + item.getPicId(), "");
            String picFilePath_c = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "c", "" + item.getPicId(), "");
            File file = new File(picFilePath_b);
            if(file.exists()) {
                file.delete();
            }
            file = new File(picFilePath_f);
            if(file.exists()) {
                file.delete();
            }
            file = new File(picFilePath_c);
            if(file.exists()) {
                file.delete();
            }
            it.remove();
        } else {
            it.remove();
        }
    }

    private void deleteDataToDb(int examId) {
        AssistantExam assistantExam = DBUtils.getInstance(mContext).getAssistantExamByExamId(examId);
        if(assistantExam != null) {
            DBUtils.getInstance(mContext).deleteExamListenByAssistantExamId(assistantExam.getId());
            DBUtils.getInstance(mContext).deleteAssistantQuestionByAssistantExamId(assistantExam.getId());
            if(assistantExam.getPictureList() != null) {
                for (PagePicture item : assistantExam.getPictureList()) {
                    DBUtils.getInstance(mContext).deletePagePictureGridByPagePictureId(item.getId());
                }
            }
            DBUtils.getInstance(mContext).deletePagePictureByAssistantExamId(assistantExam.getId());
            DBUtils.getInstance(mContext).deleteAssistantExamByExamid(assistantExam.getExamId());
        }

    }

    private void isSubmitSuccess() {
        if(mOssCount == 0 && mIsSubmitSuccess) {
            DialogXUtil.waitDialogDismiss();
            //弹提示框，提交成功
            ToastUtil.initToast("提交成功");
        } else if(!mIsSubmitSuccess){
            mIsSubmitSuccess = true;
            DialogXUtil.waitDialogDismiss();
            //弹提示框，提交失败
            ToastUtil.initToast("提交失败");
        }
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == 1) {
            //显示标题行
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pensubmit_item_1, parent, false);
            return new PenSubmitHolder_1(view);
        } else if(viewType == 2) {
            //显示图片
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pensubmit_item_2, parent, false);
            return new PenSubmitHolder_2(view);
        } else if(viewType == 3) {
            //显示第几页和删除
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pensubmit_item_3, parent, false);
            return new PenSubmitHolder_3(view);
        } else if(viewType == 4) {
            //底部最后一行空白
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pensubmit_item_4, parent, false);
            return new PenSubmitHolder_4(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof PenSubmitHolder_1) {
            ((PenSubmitHolder_1)holder).bindData(position);
        } else if (holder instanceof PenSubmitHolder_2) {
            ((PenSubmitHolder_2)holder).bindData(position);
        } else if (holder instanceof PenSubmitHolder_3) {
            ((PenSubmitHolder_3)holder).bindData(position);
        } else if (holder instanceof PenSubmitHolder_4) {
            ((PenSubmitHolder_4)holder).bindData(position);
        }
    }

    @Override
    public int getItemCount() {
        if(mData == null) {
            return 0;
        }
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mData.get(position).showType.intValue() == 0 ? 4 : mData.get(position).showType;
    }

    class PenSubmitHolder_1 extends RecyclerView.ViewHolder{

        @BindView(R2.id.iv_line_select)
        ImageView iv_line_select;
        @BindView(R2.id.tv_title_1)
        TextView tv_title_1;
        @BindView(R2.id.tv_title_2)
        TextView tv_title_2;

        public PenSubmitHolder_1( View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void bindData(int position) {
            clickListener(position);
            if(StringUtil.isEmpty(mData.get(position).getAssistantName())) {
                tv_title_1.setText("");
            } else {
                tv_title_1.setText(StringUtil.replaceAmp(mData.get(position).getAssistantName()));
            }
            if(StringUtil.isEmpty(mData.get(position).getExamName())) {
                tv_title_2.setText("");
            } else {
                tv_title_2.setText(StringUtil.replaceAmp(mData.get(position).getExamName()));
            }
            if(mData.get(position).isSelect) {
                iv_line_select.setImageResource(R.drawable.common_select_d);
            } else {
                iv_line_select.setImageResource(R.drawable.common_select_n);
            }
        }

        private void clickListener(int position) {
            iv_line_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        if(mData.get(position).isSelect) {
                            mData.get(position).isSelect = false;
                            mCurSelect--;
                            iv_line_select.setImageResource(R.drawable.common_select_n);
                        } else {
                            mData.get(position).isSelect = true;
                            mCurSelect++;
                            iv_line_select.setImageResource(R.drawable.common_select_d);
                        }
                        listener.onRefrshSelect();
                    }
                }
            });
        }

    }

    class PenSubmitHolder_2 extends RecyclerView.ViewHolder{

        @BindView(R2.id.iv_c_img)
        ImageView iv_c_img;


        public PenSubmitHolder_2( View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void bindData(int position) {
            String picFilePath_c = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "c", "" + mData.get(position).getPicId(), "");
            File file_c = new File(picFilePath_c);
            if(file_c.exists()) {

            } else {
                picFilePath_c = mData.get(position).getPictureUrl();
                //iv_c_img.setImageResource();
            }

            final String picUrl = picFilePath_c;
            if(StringUtil.isEmpty(picUrl)) {
                return;
            }
            Glide.with(mContext).asBitmap().load(picUrl).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            LogUtils.e("m1:Glde图片-成功  = " + picUrl + ", threadName = " + Thread.currentThread().getName());
                            iv_c_img.setImageBitmap(resource);
                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);
                            LogUtils.e("m1:Glde图片-失败  = " + picUrl + ", threadName = " + Thread.currentThread().getName());

                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });

            iv_c_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int curImagIndex = 0;
                    for(int i = 0; i < mData.size(); i++) {
                        if(i == position) {
                            listener.onClickPhotoView(curImagIndex);
                            break;
                        }

                        if(mData.get(i).showType.intValue() == 2) {
                            curImagIndex++;
                        }
                    }
                }
            });

        }
    }

    class PenSubmitHolder_3 extends RecyclerView.ViewHolder{

        @BindView(R2.id.tv_num_page)
        TextView tv_num_page;
        @BindView(R2.id.ll_delete_line)
        LinearLayout ll_delete_line;

        public PenSubmitHolder_3( View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void bindData(int position) {
            clickListener(position);
            tv_num_page.setText("共" + mData.get(position).pageNum + "页");
        }

        private void clickListener(int position) {
            ll_delete_line.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogXUtil.customDialogShow("确定要删除当前作业数据吗？ 删除后数据无法恢复！", "确定删除", "取消", new DialogXUtil.OnDialogXListen(){
                        @Override
                        public void onListenDialogOk() {
                            int examId = mData.get(position).getExamId();
                            Iterator<PenOffLineGridInfo> it = mData.iterator();
                            while (it.hasNext()) {
                                PenOffLineGridInfo item = it.next();
                                if(item.getExamId() != null && item.getExamId().intValue() == examId) {
                                    if(item.showType.intValue() == 1) {
                                        List<PenOffLineGridInfo> info_temp = DBUtils.getInstance(mContext).getPenOffLineGridInfoByExamId(examId);
                                        if(info_temp != null && info_temp.size() > 0) {
                                            for(PenOffLineGridInfo info_temp_item : info_temp) {
                                                info_temp_item.setBeginTime(null);
                                                info_temp_item.setFinishTime(null);
                                                info_temp_item.setOssPath(null);
                                                info_temp_item.setIsWrite(false);
                                                DBUtils.getInstance(mContext).updatePenOffLineGridInfo(info_temp_item);
                                            }
                                        }

                                        if(item.isSelect) {
                                            mCurSelect--;
                                        }
                                    }

                                    deleteDataAndFile(item, it);
                                }
                            }

                            mCount--;
                            //DBUtils.getInstance(mContext).deletePenOffLineGridInfoByExamid(examId);
                            deleteDataToDb(examId);
                            if(listener != null) {
                                listener.onRefrshSelect();
                            }
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                }
            });
        }
    }

    class PenSubmitHolder_4 extends RecyclerView.ViewHolder{


        public PenSubmitHolder_4( View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void bindData(int position) {

        }
    }

    //第一步 定义接口
    public interface OnItemClickListener {
        void onItemClick(int position);
        void onRefrshSelect();
        void onClickPhotoView(int index);
    }
    private OnItemClickListener listener;
    //第二步， 写一个公共的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

}
